package com.magist.manage.copyrights.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.magist.core.constants.Deleted;
import com.magist.core.entity.Page;
import com.magist.core.exception.BusinessException;
import com.magist.core.service.SimpleServiceImpl;
import com.magist.core.util.BeanCompareUtil;
import com.magist.core.util.BeanCopyUtil;
import com.magist.core.util.MAssertUtil;
import com.magist.manage.copyrights.dao.SupplyLinkMansMapper;
import com.magist.manage.copyrights.dto.SupplyLinkMansDto;
import com.magist.manage.copyrights.entity.SupplyInfo;
import com.magist.manage.copyrights.entity.SupplyLinkMans;
import com.magist.manage.copyrights.service.SupplyInfoService;
import com.magist.manage.copyrights.service.SupplyLinkMansService;
import com.magist.manage.enums.OpActionEnum;
import com.magist.manage.enums.OpTypeEnum;
import com.magist.manage.util.BusinessLogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SupplyLinkMansServiceImpl extends SimpleServiceImpl<SupplyLinkMans> implements SupplyLinkMansService{

	@Autowired
	private SupplyLinkMansMapper supplyLinkMansMapper;
	@Autowired
	private BusinessLogUtil businessLogUtil;
	@Autowired
	private SupplyInfoService supplyInfoService;

	@Override
	public PageInfo<SupplyLinkMans> page(Example example, Page page) {
    	PageHelper.startPage(page.getCurrPage(), page.getLimit());
    	List<SupplyLinkMans> list = this.find(example);
        PageInfo<SupplyLinkMans> pageInfo = new PageInfo(list);
		return pageInfo;
	}

	@Override
	public void saveOrUpdateSupplyLinkMan(SupplyLinkMans supplyLinkMans) {
		MAssertUtil.longerThan(supplyLinkMans.getSupplyId(),0,"供应商ID不能为空");
		MAssertUtil.longerThan(supplyLinkMans.getLinkName(),0,"姓名不能为空");
		MAssertUtil.longerThan(supplyLinkMans.getLinkMobile(),0,"电话不能为空");
		
		if(!StringUtils.isEmpty(supplyLinkMans.getId())) {
			this.update(supplyLinkMans);
		} else {
			SupplyLinkMans temp=new SupplyLinkMans();
			temp.setSupplyId(supplyLinkMans.getSupplyId());
			temp.setDeleted(Deleted.NO_STR);
			List<SupplyLinkMans> supplyLinkMansList=this.find(temp);
			if(!CollectionUtils.isEmpty(supplyLinkMansList)&&supplyLinkMansList.size()>4){
				throw new BusinessException("最多添加5个联系人");
			}
			supplyLinkMans.setId(this.getNewId());
			this.insert(supplyLinkMans);
		}
	}

	@Override
	public void saveOrUpdateSupplyLinkMans(String supplyId, List<SupplyLinkMansDto> supplyLinkMansDtos) {
		int size = supplyLinkMansDtos.size();
		if (size >5){
			throw new BusinessException("最多添加5个联系人");
		}
		SupplyInfo supplyInfo = supplyInfoService.getById(supplyId);
		if(ObjectUtils.isEmpty(supplyInfo)) {
			return;
		}
		// 标题
		StringBuffer opTitle = new StringBuffer("修改供应商联系人:" + supplyInfo.getCompanyName());
		// 内容
		StringBuffer opContent = new StringBuffer();
		// 过滤空的
		supplyLinkMansDtos = supplyLinkMansDtos.stream().filter(dto -> !(StringUtils.isEmpty(dto.getLinkMail()) && StringUtils.isEmpty(dto.getLinkName()) && StringUtils.isEmpty(dto.getLinkMobile()) && StringUtils.isEmpty(dto.getRemark()))).collect(Collectors.toList());
		// 查询联系人
		List<SupplyLinkMans> supplyLinkMans = this.findBySupplyId(supplyId);
//		if (CollectionUtils.isEmpty(supplyLinkMansDtos)) {
//			return;
//		}
		supplyLinkMansDtos.forEach(supplyLinkMansDto -> {
			MAssertUtil.notNull(supplyLinkMansDto.getLinkName(), "姓名不能为空");
			MAssertUtil.notNull(supplyLinkMansDto.getLinkMobile(), "手机号不能为空");
			// 校验长度
			MAssertUtil.shorterThan(supplyLinkMansDto.getLinkName(),20,"姓名过长");

			MAssertUtil.isMobile(supplyLinkMansDto.getLinkMobile(),"手机号格式错误");
			MAssertUtil.nullOrShorterThan(supplyLinkMansDto.getLinkMail(),50,"邮箱过长");
			MAssertUtil.isNullOrEmail(supplyLinkMansDto.getLinkMail(),"邮箱格式错误");
			MAssertUtil.nullOrShorterThan(supplyLinkMansDto.getRemark(),50,"备注过长");
		});



		// 分类有id和无id
		List<SupplyLinkMans> updateLinkMans = BeanCopyUtil.copy(supplyLinkMansDtos.stream().filter(dto -> !StringUtils.isEmpty(dto.getId())).collect(Collectors.toList()),SupplyLinkMans.class);
		List<SupplyLinkMans> addLinkMans = BeanCopyUtil.copy(supplyLinkMansDtos.stream().filter(dto -> StringUtils.isEmpty(dto.getId())).collect(Collectors.toList()),SupplyLinkMans.class);




		if (!CollectionUtils.isEmpty(addLinkMans)) {
			opTitle.append("添加联系人:");
			opContent.append("添加联系人:");
			// 添加
			for (SupplyLinkMans addLinkMan : addLinkMans) {
				addLinkMan.setId(this.getNewId());
				addLinkMan.setSupplyId(supplyId);
				this.insert(addLinkMan);
				opTitle.append(addLinkMan.getLinkName() + ",");
				BeanCompareUtil.joinInfo(opContent, addLinkMan.getLinkName(), BeanCopyUtil.copy(addLinkMan,SupplyLinkMansDto.class), true);
			}

		}

		// 更新
		if (!CollectionUtils.isEmpty(updateLinkMans)) {
			opTitle.append("更新联系人:");
			opContent.append("更新联系人:");
			for (SupplyLinkMans updateLinkMan : updateLinkMans) {
				// 查询原来的,作比较
				SupplyLinkMansDto oldDto = BeanCopyUtil.copy(this.getById(updateLinkMan.getId()), SupplyLinkMansDto.class);
				this.update(updateLinkMan);
				opTitle.append(updateLinkMan.getLinkName() + ",");
				BeanCompareUtil.joinCompare(opContent, updateLinkMan.getLinkName(),oldDto,BeanCopyUtil.copy(updateLinkMan,SupplyLinkMansDto.class),true);
			}

		}
//		updateLinkMans.forEach(updateLinkMan->this.update(updateLinkMan));

		// 要删除的名单
		if (!CollectionUtils.isEmpty(supplyLinkMans)) {

			List<String> exitIds = supplyLinkMans.stream().map(SupplyLinkMans::getId).collect(Collectors.toList());
			List<String> updateIds = updateLinkMans.stream().map(SupplyLinkMans::getId).collect(Collectors.toList());
			exitIds.removeAll(updateIds);

			if (!CollectionUtils.isEmpty(exitIds)) {
				opTitle.append("删除联系人:");
				opContent.append("删除联系人:");
				for (String delId : exitIds) {
					SupplyLinkMans delMan = this.getById(delId);
					opTitle.append(delMan.getLinkName() + ",");
					opContent.append(delMan.getLinkName() + ",");
					this.delete(delId);
				}
				
//			exitIds.forEach(delId->this.delete(delId));
			}

		}

		try {
			businessLogUtil.recordBusinessLog(OpActionEnum.MIX.getCode(),OpTypeEnum.SupplyLinkMans.getCode(),null,opTitle.toString(),opContent.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private List<SupplyLinkMans> findBySupplyId(String supplyId) {
		SupplyLinkMans supplyLinkMans = new SupplyLinkMans();
		supplyLinkMans.setSupplyId(supplyId);
		return this.find(supplyLinkMans);
	}

	public void delete(String id) {
		SupplyLinkMans supplyLinkMans = this.getById(id);
		if(!ObjectUtils.isEmpty(supplyLinkMans)) {
			delete(supplyLinkMans);
		}
	}


}
